package com.lei.demo.dao;

import com.lei.demo.entity.User;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * Created by Shinelon on 2017/6/8.
 */
@Repository
@Transactional
public class UserDAO {
    @Autowired
    private SessionFactory sessionFactory;

    public List<User> getAllUser(){
        String hsql="from user";
        Session session = getCurrentSession();
        Query query = session.createQuery(hsql);

        return query.list();
    }

    public void save(User user) {
        Session session = getCurrentSession();
        session.save(user);
    }

    public void update(User user) {
        Session session = getCurrentSession();
        session.update(user);
    }

    public void  delete(User user) {
        Session session = getCurrentSession();
        session.delete(user);
    }

    public User findById(int id) {
        Session session = getCurrentSession();
        return (User)session.get(User.class,id);
    }

    public List<User> findUsers(String name) {
        return findByCriteria(Restrictions.like("name", name, MatchMode.START));
    }

    public List<User> findByCriteria(Criterion criterion) {
        Criteria criteria = getCurrentSession().createCriteria(User.class);
        criteria.add(criterion);
        return criteria.list();
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }
}
